package com.joshua.userservice.rmi;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

public class EntityService implements IEntityService {

	@Autowired
	public SessionFactory sessionFactory;

	public ThreadLocal<Session> session = new ThreadLocal<Session>();

	public Session currentSession() throws HibernateException {
		Session s = session.get();
		if (s == null) {
			s = sessionFactory.openSession();
			session.set(s);
		}
		return s;
	}

	public void closeSession() throws HibernateException {
		Session s = session.get();
		if (s != null)
			s.close();
		session.set(null);
	}


	public void persist(Object o) {
		Session session = currentSession();
		Transaction tx = session.beginTransaction();
		session.persist(o);
		tx.commit();
		closeSession();
	}

	public void merge(Object o) {
		Session session = currentSession();
		Transaction tx = session.beginTransaction();
		session.merge(o);
		tx.commit();
		closeSession();

	}

	public void delete(Object o) {
		Session session = currentSession();
		Transaction tx = session.beginTransaction();
		session.delete(o);
		tx.commit();
		closeSession();

	}

	public Object getObject(Class c, long id) {
		Session session = currentSession();
		
		Transaction tx = session.beginTransaction();
		Object object = session.get(c, id);
		tx.commit();
		closeSession();
		
		return object;
	}
	
	public List getAll(Class c)
	{
		Session session = currentSession();
		
		Transaction tx = session.beginTransaction();
		List objs = session.createQuery("from" + c.toString().replace("class", "")).list();
		tx.commit();
		
		closeSession();
		return objs;
	}

}
